/**   
* @Title: CrashHandler.java 
* @author 6335yz   
* @date 2015年8月21日 上午11:15:42 
*/
package com.shanghaionstar.utils;

import android.content.Context;
import android.os.Environment;
import android.util.Log;

import com.onstar.cn.common.log.LogManager;
import com.onstar.cn.common.util.CommonUtil;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.Thread.UncaughtExceptionHandler;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Calendar;

/** 
* @ClassName: CrashHandler 
* @Description: process error when app crash
* @author 6335yz
* @date 2015年8月21日 上午11:15:42 
*/
public class CrashHandler implements UncaughtExceptionHandler {


	private UncaughtExceptionHandler mDefaultHandler;
	private Context context;
	private CarshHandlerListener lietener;
	private LogManager log;

	public CrashHandler(Context context) {
		this.context = context;
		mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
		log = LogManager.getInstance();
		Thread.setDefaultUncaughtExceptionHandler(this);
	}

	@Override
	public void uncaughtException(Thread thread, Throwable ex) {
		// 删除地图缓存文件
		CommonUtil.deleteFile(new File("sdcard/AMap"));
//		OperateB2CUtil.operateEventReport(Event.Crash, ex.getMessage(), context, "2");
//		CommonUtil.operateB2CReport(Event.Crash, ex.getMessage(), context);
//		if (writeFile(ex)) {
//			mDefaultHandler.uncaughtException(thread, ex);
//		} else {
//			mDefaultHandler.uncaughtException(thread, ex);
//		}
		LogManager.getInstance().e(Log.getStackTraceString(ex));
		BusinessUtil.refreshPolling(context);
		writeFile(ex);

//		upload(Log.getStackTraceString(ex));
		
//		android.os.Process.killProcess(android.os.Process.myPid());
//		System.exit(1);
		 /* User clicked OK so do some stuff */
		// 取消polling
		BusinessUtil.refreshPolling(context);
		BusinessUtil.clearOnstarAppContext(context);

		if(lietener!=null)lietener.result();
//		mDefaultHandler.uncaughtException(thread, ex);
//		Runtime.getRuntime().exit(0);
//		Runtime.getRuntime().gc();
	}

	/**
	 * @author zhang kai
	 * @description 清理文件夹 防止文件过多打不开
	 * 超过额定值就清除一半
	 */
	private void cleanDir(int maxNum) {
		File dir = new File(getFilePath());
		File[] files = dir.listFiles(new FilenameFilter() {
			@Override
			public boolean accept(File dir, String filename) {
				return filename.startsWith("crash-");
			}
		});
		if (files != null && files.length > maxNum) {
			Arrays.sort(files);
			for (int i = 0; i < maxNum / 2; i++) {
				files[i].delete();
			}
		}
	}

	private boolean writeFile(final Throwable ex) {
		if (ex == null) {
			return false;
		}
		cleanDir(50);
		String log = Log.getStackTraceString(ex);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
		String fileName = "crash-" + sdf.format(Calendar.getInstance().getTime()) + ".log";
		File file = new File(getFilePath(), fileName);
		PrintWriter pw = null;
		FileOutputStream fis = null;
		try {
			fis = new FileOutputStream(file, false);
			pw = new PrintWriter(fis);
			pw.write(log);
		} catch (FileNotFoundException e) {
			return false;
		}finally {
			if(fis != null)
				try {
					fis.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			if(pw != null)
				pw.close();
		}
		return true;
	}

//	private void upload(String error) {
//		FileUpload.getInstance(context).upload(error);
//	}

	private String getFilePath() {
		String filePath = "";
		if (!CommonUtil.isNull(Environment.getExternalStorageState())&&Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
			filePath = "/mnt/sdcard" + File.separator + "onstar";
		} else {
			filePath = context.getApplicationContext().getCacheDir().getAbsolutePath() + File.separator + "onstar";
		}
		File file = new File(filePath + File.separator);
		if (!file.exists()) {
			file.mkdirs();
		}
		return filePath;
	}
	
	public void setLietener(CarshHandlerListener lietener) {
		this.lietener = lietener;
	}

	public interface CarshHandlerListener{
		void result();
	}
}
